import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';

import '../config/app_theme.dart';
import '../config/app_url_address.dart';
import '../pages/widget/JoyBuyUpdateDialog.dart';

///JoyActionService
class JoyActionService {
  static Future<void> LitlogUserAction(String action,String spuNo, [String actionCode = '101']) async {
    try {
      // Determine the current platform
      String platform = 'Litbuy-Sheets';
      if (Platform.isIOS) {
        platform += '-iOS-App';
      } else if (Platform.isAndroid) {
        platform += '-Android-App';
      } else {
        platform += '-App'; // Default suffix
      }

      // Build request parameters
      final Map<String, String> requestBody = {
        'action': action,
        'actionCode': actionCode,
        'platform': platform,
        'spuNo': spuNo?? '',
      };

      // Send POST request - use x-www-form-urlencoded format
      final response = await http.post(
        Uri.parse("https://gateway.plug4.me" + '/api/user/action/userActionLog/action'),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: requestBody.entries.map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}').join('&'),
      );

      // Process response
      if (response.statusCode == 200) {
        final responseData = jsonDecode(response.body);
        debugPrint('Action log success: ${responseData['success']}');
      } else {
        debugPrint('Action log failed with status: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Error logging user action: $e');
    }
  }

  // Get version information from your own server
  static Future<void> LitVersionInfo(BuildContext context, {bool showUpdateDialog = true}) async {
    try {
      // This should be the code to get version information from your own server

      // 构建请求参数
      final Map<String, String> requestBody = {
        'appName': Platform.isIOS ? 'iOS-Litbuy-Sheets' : 'Android-Litbuy-Sheets',
      };

      // Build request URL and encode parameters
      final queryString = requestBody.entries.map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}').join('&');
      final uri = Uri.parse(baseHostUrl + joyversionInfo + '?' + queryString);

      // Send GET request
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
          'Accept': 'application/json; charset=utf-8',
        },
      );

      if (response.statusCode == 200) {

        final packageInfo = await PackageInfo.fromPlatform();

        final data = json.decode(utf8.decode(response.bodyBytes));

        final datajson = data["result"];

        debugPrint('version info: ${datajson}');

        final String latestVersion = datajson['version'] ?? packageInfo.version;

        final String versionDesc = datajson['versionDesc'];
        //0 means update is needed, 1 means no update is needed
        final String versionType = datajson['versionType'] ?? 1;

        AppTheme.UserAppTheme = datajson['appState'] ?? '1';

        if(latestVersion == packageInfo.version) {


        } else {

          if(showUpdateDialog) {
           
            // When versionType is 0, pop up the update dialog
          if (versionType == '0') {
            // Using BuildContext needs to be executed in the UI thread
            // Use WidgetsBinding to ensure running on the UI thread
            // WidgetsBinding.instance.addPostFrameCallback((_) {
            //   // Get global context
            //   final context = Routers.navigatorKey.currentContext;
            //   if (context != null) {
            //
            //   }
            // });
            showDialog(
              context: context,
              builder: (context) => LitUpdateDialog(versionDesc: versionDesc),
            );
          }
          }

         
        }
        debugPrint('version Update data: ${response}');

      } else {
        throw 'Server returned error: ${response.statusCode}';
      }
    } catch (e) {
      // If it fails, use the current version
      // _latestVersion = _currentVersion;
      // _needUpdate = false;
      // _errorMessage = 'Failed to get the latest version information: $e';
    }
  }

  /// 系统浏览器打开（Android: 默认浏览器 / iOS: Safari）
  static Future<bool> LitopenInSystemAppBrowser(String url) async {
    try {
      final Uri primary = LitHttpUrl(url);

      // 优先直接尝试外部浏览器（部分设备 canLaunchUrl 返回 false 但实际可打开）
      try {
        final ok = await launchUrl(primary, mode: LaunchMode.externalApplication);
        if (ok) return true;
      } catch (_) {}

      // 次优：尝试 in-app 浏览器，保证至少能打开
      try {
        final ok = await launchUrl(primary, mode: LaunchMode.inAppBrowserView);
        if (ok) return true;
      } catch (_) {}

      // 再尝试平台默认
      try {
        final ok = await launchUrl(primary, mode: LaunchMode.platformDefault);
        if (ok) return true;
      } catch (_) {}

      // 兜底：尝试替换协议 http <-> https 与编码
      final String swapped = primary.scheme == 'https'
          ? primary.toString().replaceFirst('https://', 'http://')
          : primary.toString().replaceFirst('http://', 'https://');
      final Uri secondary = LitHttpUrl(swapped);

      try {
        final ok = await launchUrl(secondary, mode: LaunchMode.externalApplication);
        if (ok) return true;
      } catch (_) {}

      try {
        final ok = await launchUrl(secondary, mode: LaunchMode.inAppBrowserView);
        if (ok) return true;
      } catch (_) {}

      return false;
    } catch (e) {
      debugPrint('Open in system browser error: $e');
      return false;
    }
  }

  static Uri LitHttpUrl(String url) {
    String trimmed = url.trim();
    if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
      trimmed = 'https://$trimmed';
    }
    Uri? uri = Uri.tryParse(trimmed);
    if (uri == null) {
      // 尝试编码再解析
      uri = Uri.tryParse(Uri.encodeFull(trimmed));
    }
    return uri ?? Uri.parse('https://$url');
  }

  static Future<void> openLitAppStore() async {
    final Uri url;
    if (Platform.isIOS) {
      // Replace with your iOS app's App Store ID
      url = Uri.parse('https://apps.apple.com/app/id6753975667');
    } else if (Platform.isAndroid) {
      // Get app package name
      final packageInfo = await PackageInfo.fromPlatform();
      //Use Google Play Store link
      url = Uri.parse('https://play.google.com/store/apps/details?id=${packageInfo.packageName}');

    } else {
      return;
    }

    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    }
  }

  // Open Discord app
  static Future<void> LitaunchDiscordApp(String url) async {

    await JoyActionService.LitlogUserAction(url, '103');
    // Extract invitation code
    String inviteCode = '';
    if (url.contains('/invite/')) {
      inviteCode = url.split('/invite/').last;
    } else if (url.contains('discord.gg/')) {
      inviteCode = url.split('discord.gg/').last;
    }

    // Remove possible extra parameters
    inviteCode = inviteCode.split('?').first;
    inviteCode = inviteCode.split('&').first;

    // Build deep link
    final Uri discordUri = Uri.parse('discord://discord.com/invite/$inviteCode');
    final Uri fallbackUri = Uri.parse(url);

    try {
      // First check if Discord app can be launched
      bool canLaunchDiscord = await canLaunchUrl(discordUri);

      if (canLaunchDiscord) {
        // If Discord app can be launched, launch it directly
        final bool launched = await launchUrl(
          discordUri,
          mode: LaunchMode.externalApplication,
        );

        if (launched) {
          debugPrint('Successfully opened Discord app');
          return;
        }
      }

      // If Discord app cannot be launched or fails to launch, open it in browser
      final bool browserLaunched = await launchUrl(
        fallbackUri,
        mode: LaunchMode.externalApplication,
      );

      if (browserLaunched) {
        debugPrint('Opened Discord in browser');
      } else {
        debugPrint('Failed to open Discord');
      }

    } catch (e) {
      debugPrint('Error launching Discord: $e');
      // Try to open in browser
      try {
        await launchUrl(
          fallbackUri,
          mode: LaunchMode.externalApplication,
        );
        debugPrint('Fallback: Opened in browser');
      } catch (e) {
        debugPrint('Could not open Discord: $e');
      }
    }
  }

  /// 打开应用商店评价页面
  static Future<void> openAppLitStoreRating() async {
    final Uri url;
    if (Platform.isIOS) {
      // iOS使用特定的评价URL格式
      url = Uri.parse('https://apps.apple.com/app/id6753975667?action=write-review');
    } else if (Platform.isAndroid) {
      // 获取应用包名
      final packageInfo = await PackageInfo.fromPlatform();
      // Android使用Google Play Store评价链接
      url = Uri.parse('https://play.google.com/store/apps/details?id=${packageInfo.packageName}&showAllReviews=true');
    } else {
      return;
    }

    if (await canLaunchUrl(url)) {
      await launchUrl(url, mode: LaunchMode.externalApplication);
    }
  }

  /// 记录打开链接行为
  static Future<void> FindlogOpenLink(String url,String itemNo) async {
    await LitlogUserAction(url, '101',itemNo);
  }

  /// 记录复制链接行为
  static Future<void> FindlogCopyLink(String url,String itemNo) async {
    await LitlogUserAction(url, '102',itemNo);
  }
}
